package com.briup;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.ListUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.lang.invoke.CallSite;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 监听器实现读的操作
 * 1.将到的每行数据封装到list集合
 * 2.通过mapper对象保存到数据库
 * 3.程序分批插入保存数据，每批大小和容量相同
 */
public class DempDataListener implements ReadListener<DemoData> {

    private DemoDataMapper mapper;
    private int batchCount = 5;
    private List<DemoData> list = new ArrayList<>(50);//数组扩容要实现元素的复制到另一个数组上面
    private List list1 = ListUtils.newArrayListWithExpectedSize(batchCount); //检查参数是否合法
    public DempDataListener() {
    }

    public DempDataListener(DemoDataMapper mapper) {
        this.mapper = mapper;
    }

    public void invoke(DemoData demoData, AnalysisContext analysisContext) {
        list.add(demoData);
        if (list.size() >= 50){
            //将50条数据分批保存到数据库
            save();
            //清空容器，重新存储下一批数据
            //list.clear();

            list = new ArrayList<>(50);
        }
    }


    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("数据的条数是："+list.size());
        //
        if (list.size() != 0){
            save();
        }

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        System.out.println("发生了异常");
        //如果是用户输入导致数据异常，提示用户数据错误
        if (exception instanceof ExcelDataConvertException){
            //提示用户详细信息
            ExcelDataConvertException ex = (ExcelDataConvertException) exception;
            Integer rowIndex = ex.getRowIndex();
            Integer columnIndex = ex.getColumnIndex();
            String value = ex.getCellData().getStringValue();
            throw new  RuntimeException("用户提供的文件错误");
        }
        //当异常发生，是否将剩余的数据保存到数据库
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        //获取表格的头信息
        Collection<ReadCellData<?>> values = headMap.values();
        List<String> heads = headMap.values().stream()
                .map(readCellData -> readCellData.getStringValue()).collect(Collectors.toList());
        System.out.println("表格头信息："+heads);
        Map<Integer, String> map = ConverterUtils.convertToStringMap(headMap, context);
        System.out.println(map);
    }

    public void save(){
        mapper.insertList(list);
    }
}
